import React, {useState, useEffect} from 'react';
import style from './App.module.css';
import robots from './mockdata/robots.json'
import Robot from './components/Robot'
import RobotDiscount from './components/RobotDiscount'
import logo from './assets/images/logo.svg'
import ShoppingCart from './components/ShoppingCart'

interface Props {
  userName: string
}
interface State {
  robotGallery: any[];
  count: number
}

const App : React.FC<Props> = (props) => {
  const [count, steCount] = useState<number>(0)
  const [robotGallery, steRobotGallery] = useState<any>([])
  const [loading, setLoading] = useState<boolean>(false)
  const [error, setError] = useState<string>()

  useEffect(() => {
    document.title = `点击次数为${count}`
  }, [count])
  useEffect(() => {
    const fetchData = async () => {
      setLoading(true)
      try {
        const responses = await fetch('http://jsonplaceholder.typicode.com/users')
        const data = await responses.json()
        steRobotGallery(data)
      } catch(e: any) {
        setError(e.message)
      }
      setLoading(false)
    }
    fetchData()
    // .then(response => {
    //   return response.json()
    // })
    // .then(res => {
    //   return steRobotGallery(res)
    // })
  }, [])
  // // 生命周期第一阶段: 创建
  // // 在创建好组件DOM元素后,挂载进页面的时候调用
  // componentDidMount() {
  //   fetch('http://jsonplaceholder.typicode.com/users').then(response => {
  //     // console.log(response.json)
  //     return response.json()
  //   }).then(res => {
  //     console.log(res)
  //     return this.setState({
  //       robotGallery: res
  //     })
  //   })
  // }

    return (
      <div className={style.app}>
        <div className={style.appHeader}>
          <img src={logo} className={style.appLogo} />
          <h1>罗伯特机器人</h1>
        </div>
        <h2>
          {props.userName}
        </h2>
        <button onClick={() => {
          steCount(count+1)
          // this.setState((state, props) => {
          //   return {
          //     count: state.count + 1
          //   }
          // } , () => {
          //   console.log('count', count)
          // })
        }}>click</button>
        <span>count: {count}</span>
        <ShoppingCart></ShoppingCart>
        {!error || error !== '' && <div>{error}</div> }
        { 
          !loading ? 
          <div className={style.robotList}>
            {
              robotGallery.map((r,index) => {
                return (
                  index % 2 == 0 ?
                  <RobotDiscount id={r.id} email={r.email} name={r.name}></RobotDiscount> :
                  <Robot id={r.id} email={r.email} name={r.name} />
                )
              })
            }
          </div> : '正在加载中...'
        }
      </div>
    );

}

export default App;
